package com.tungse;

import cn.hutool.core.map.MapUtil;

import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 测试线程池下InheritableThreadLocal线程变量失效的场景
 */
public class TestInheritableThreadLocal2 {

    private static final InheritableThreadLocal<Map<String, String>> ithreadLocal = new InheritableThreadLocal<>();
//    private static final ThreadLocal<String> threadLocal = new ThreadLocal<>();

    // 固定大小的线程池，保证线程复用
    private static final ExecutorService executorService = Executors.newFixedThreadPool(1);

    public static void main(String[] args) throws InterruptedException {
        ithreadLocal.set(MapUtil.of("张三", "20"));
        executorService.execute(() -> {
            System.out.println("1"+ithreadLocal.get());
            ithreadLocal.get().put("李四", "30");
            System.out.println("2"+ithreadLocal.get());
        });
        Thread.sleep(1000);
        System.out.println("3"+ithreadLocal.get());
        ithreadLocal.remove();
        ithreadLocal.set(MapUtil.of("王", "30"));
        // 线程复用再取还是 main线程 变量1
        executorService.execute(() -> {
            System.out.println("4"+ithreadLocal.get());
        });
    }
}